package com.yj.cloudnote.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBObject;
import com.yj.cloudnote.mongo.dao.DirDao;
import com.yj.cloudnote.service.DirService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class DirServiceImpl implements DirService {
    @Autowired
    private DirDao dirDao;

    /**
     * @Author: jy
     * @Description:
     * @Date: 10:23 2018/4/26
     */
    @Override
    public Boolean initDir(DBObject dbObject) {
        dirDao.initDir(dbObject);
        return true;
    }

    /**
     * @Author: jy
     * @Description:
     * @Date: 10:23 2018/4/26
     */
    @Override
    public Object[] getDirByUName(String username) {
        DBObject dbObject = dirDao.getDirOne(username);
        Map dbo2map = dbObject.toMap();
        Object[] dirs = ((BasicDBList)dbo2map.get("directory")).toArray();
        return dirs;
    }

    /**
     * @Author: jy
     * @Description:
     * @Date: 12:46 2018/4/26
     */
    @Override
    public int getDirCount(String username) {
        DBObject dbObject = dirDao.getDirCount(username);
        int dirCount = (int)dbObject.get("dirCount");
        return dirCount;
    }

    /**
     * @Author: jy
     * @Description:
     * @Date: 12:46 2018/4/26
     */
    @Override
    public int getFileCount(String username) {
        Map<String,Object> query = new HashMap<>();
        query.put("username",username);
        Map<String,Object> key = new HashMap<>();
        key.put("fileCount",1);
        DBObject dbObject = dirDao.getOne(query,key);
        int fileCount = (int)dbObject.get("fileCount");
        return fileCount;
    }

    /**
     * @Author: jy
     * @Description:
     * @Date: 14:21 2018/4/26
     */
    @Override
    public void updateDir(Map<String,Object> params) {
        String username = (String) params.get("username");
        int dirCount = (int) params.get("dirCount");
        int fileCount = (int) params.get("fileCount");
        DBObject dirs = (DBObject) params.get("dirs");
        Map<String,Object> where = new HashMap<>();
        where.put("username",username);
        Map<String,Object> set = new HashMap<>();
        set.put("dirCount",dirCount);
        set.put("directory",dirs);
        set.put("fileCount",fileCount);
        dirDao.updateOne(where,set);
    }
}
